package com.engine.jucailinkq.attendance.attendanceanalysis.cmd;

import com.alibaba.fastjson.JSONObject;
import com.engine.jucailinkq.attendance.enums.CheckBoxEnum;
import com.engine.jucailinkq.attendance.enums.ClassSegmentTypeEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.common.util.ExtensionClassHolder;
import com.engine.jucailinkq.common.util.Utils;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 计算获取归属于分析日期的打卡数据
 */
@Slf4j
public class GetClockInTimeListCmd extends AbstractCommonCommand<Map<String,Object>> {
    public GetClockInTimeListCmd(Map<String, Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        //分析日期
        String needGetDate = Util.null2String(params.get("date"));
        //打卡数据
        List<Map<String,Object>> clockInTimeList = (List<Map<String,Object>>)params.get("clockInTimeList");
        //班次数据
        Map<String, List<Map<String,Object>>> schedulingResultCollect = (Map<String, List<Map<String,Object>>>)params.get("schedulingResultCollect");
        //出勤结果日期对应的进出数据
        Map<String,Map<String,Object>> clockInTimeMap = (Map<String,Map<String,Object>>)params.get("clockInTimeMap");
        //当天班次
        List<Map<String,Object>> needGetDateScheduling = schedulingResultCollect.get(needGetDate);
        //
        Map<String, List<Map<String,Object>>> collect = (Map<String, List<Map<String,Object>>>)params.get("clockInTimeCollect");
        //分析人员
        String userId = Util.null2String(params.get("userId"));
        //
        List<Map<String, Object>> workHourItems = (List<Map<String, Object>>)(params.get("workHourItems"));

        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("GetClockInTimeListCmd params:" + JSONObject.toJSONString(params));

        String ifPriority = "";
        if (workHourItems != null && workHourItems.size() > 0) {
            ifPriority = Util.null2String(workHourItems.get(0).get("hlpbyxsyzhgs"));
        }
        //没有打卡记录
        if (clockInTimeList == null ||clockInTimeList.size() == 0){
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",Lists.newArrayList());

            return resultMap;
        }

        if (needGetDateScheduling == null || needGetDateScheduling.size() == 0 || ifPriority.equals(CheckBoxEnum.CHECKED.getKey())){
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",getEarliestTime(clockInTimeMap,clockInTimeList));
            return resultMap;
        }


        List<Map<String, Object>> scheduleList = needGetDateScheduling.stream().filter(e -> {
            if (!ClassSegmentTypeEnum.REST_AND_DINE.getKey().equals(e.get("bdlx")) && !ClassSegmentTypeEnum.REST_PERIOD.getKey().equals(e.get("bdlx")) &&
                    !ClassSegmentTypeEnum.DINING_PERIOD.getKey().equals(e.get("bdlx")) && (CheckBoxEnum.CHECKED.getKey().equals(e.get("ksdk")) || CheckBoxEnum.CHECKED.getKey().equals(e.get("jsdk")))){
                return true;
            }else {
                return false;
            }
        }).collect(Collectors.toList());
        if (scheduleList == null || scheduleList.size() == 0){
            //没有排班
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",getEarliestTime(clockInTimeMap,clockInTimeList));

            return resultMap;
        }

        Map<String, Object> firstKsdkSchedule = null;
        Map<String, Object> lastKsdkSchedule = null;
        for (int i=0;i<scheduleList.size();i++){
            if (CheckBoxEnum.CHECKED.getKey().equals(scheduleList.get(i).get("ksdk"))){
                firstKsdkSchedule = scheduleList.get(i);
                break;
            }
        }
        for (int j=scheduleList.size()-1;j>=0;j--){
            if (CheckBoxEnum.CHECKED.getKey().equals(scheduleList.get(j).get("jsdk"))){
                lastKsdkSchedule = scheduleList.get(j);
                break;
            }
        }
        //当天班次最早会打卡的时间点
        String earliestTime = "";
        if (firstKsdkSchedule != null){
            earliestTime = Utils.getkssjEarliestTime(firstKsdkSchedule,needGetDate);
        }
        String earlyTime = Utils.getkssjEarliestTime(needGetDateScheduling.get(0),needGetDate);
        if (earliestTime == "" || DateUtil.getTime(earliestTime).compareTo(DateUtil.getTime(earlyTime)) > 0){
            earliestTime = earlyTime;
        }
        //当天班次最晚会打卡的时间点
        String lastestTime = "";
        if (lastKsdkSchedule != null){
            lastestTime = Utils.getjssjLastestTime(lastKsdkSchedule,needGetDate);
        }
        String lastTime = Utils.getjssjLastestTime(needGetDateScheduling.get(needGetDateScheduling.size()-1),needGetDate);
        if (lastestTime == "" || DateUtil.getTime(lastestTime).compareTo(DateUtil.getTime(lastTime)) < 0){
            lastestTime = lastTime;
        }
        baseBean.writeLog("GetClockInTimeListCmd earliestTime、lastestTime：" + earliestTime + "、" + lastestTime);

        boolean mark = false;
       // if (DateUtil.getTime(earliestTime).compareTo(DateUtil.getTime(needGetDate+" 00:00:00")) < 0){
            //当最早打卡时间点在前一天时，获取前一天的出勤结果打卡数据
            String earliestDate = DateUtil.beforeDay(needGetDate,1);
            Map<String,Object> clockIntime = clockInTimeMap.get(earliestDate);

            if (clockIntime == null || clockIntime.size()==0){
                String sql = "select rq,j1,c1,j2,c2,j3,c3,j4,c4,j5,c5,j6,c6,j7,c7,j8,c8 from uf_jcl_kq_cqjg where ygid=? and rq>=? and rq<=?";
                List<Map<String,Object>> attendanceResult = DbTools.getSqlToList(sql,userId,DateUtil.beforeDay(earliestDate,1),earliestDate);
                Map<String, List<Map<String,Object>>> attendanceCollect = attendanceResult.stream().collect(Collectors.groupingBy(e->e.get("rq").toString()));
                clockIntime = attendanceCollect.get(earliestDate) == null?null:attendanceCollect.get(earliestDate).get(0);
                if (clockIntime == null || clockIntime.size()==0){
                    //取不到当天的就再往前取一天
                    clockIntime = attendanceCollect.get(DateUtil.beforeDay(earliestDate,1)) == null?null:attendanceCollect.get(DateUtil.beforeDay(earliestDate,1)).get(0);
                }
            }
            if (clockIntime !=null && clockIntime.size()>0){
                for (int i=8;i>0;i--){
                    String in  = Util.null2String(clockIntime.get("j"+i));
                    String out  = Util.null2String(clockIntime.get("c"+i));
                    if (!"".equals(out) && !"NULL".equals(out)){
                        if (DateUtil.getTime(out).compareTo(DateUtil.getTime(earliestTime)) > 0){
                            mark = true;
                            earliestTime = out;
                        }
                        break;
                    }else if (!"".equals(in) && !"NULL".equals(in)){
                        if (DateUtil.getTime(in).compareTo(DateUtil.getTime(earliestTime)) > 0){
                            mark = true;
                            earliestTime = in;
                        }
                        break;
                    }
                }
            }
      //  }
        if (mark){
            earliestTime = DateUtil.AfterSeconds(earliestTime,1);
        }
        baseBean.writeLog("GetClockInTimeListCmd earliestTime:" + earliestTime);
        log.debug("earliestTime :[{}],lastestTime: [{}]",earliestTime,lastestTime);
        String finalEarliestTime = earliestTime;
        String finalLastestTime = lastestTime;
        List<Map<String,Object>> effectiveclockInTimeList = clockInTimeList.stream().filter(e->{
            String signDate = e.get("signdate")+" "+e.get("signtime");
            if ("".equals(Util.null2String(finalEarliestTime)) && "".equals(Util.null2String(finalLastestTime))){
                return true;
            }else if ("".equals(Util.null2String(finalEarliestTime)) && !"".equals(Util.null2String(finalLastestTime))){
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalLastestTime)) <=0){
                    return true;
                }else {
                    return false;
                }

            }else if (!"".equals(Util.null2String(finalEarliestTime)) && "".equals(Util.null2String(finalLastestTime))){
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalEarliestTime)) >=0){
                    return true;
                }else {
                    return false;
                }

            }else{
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalEarliestTime)) >=0 && DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalLastestTime)) <=0){
                    return true;
                }else {
                    return false;
                }
            }
        }).collect(Collectors.toList());
        Map<String,Object> resultMap = Maps.newHashMap();
        clearRepeatClock(effectiveclockInTimeList);
        resultMap.put("resultList",effectiveclockInTimeList);

        return resultMap;
    }

    public List<Map<String,Object>> getEarliestTime(Map<String,Map<String,Object>> clockInTimeMap,List<Map<String,Object>> clockInTimeList){
        String date = Util.null2String(params.get("date"));
        String beforeOneDay = DateUtil.beforeDay(date ,1);
        String userId = Util.null2String(params.get("userId"));
        String earliestTime = date+" 00:00:00";
        Map<String,Object> clockIntime = clockInTimeMap.get(date);
        if (clockIntime == null || clockIntime.size() == 0){
            String sql = "select rq,j1,c1,j2,c2,j3,c3,j4,c4,j5,c5,j6,c6,j7,c7,j8,c8 from uf_jcl_kq_cqjg where ygid=? and rq>=? and rq<=?";
            List<Map<String,Object>> attendanceResult = DbTools.getSqlToList(sql,userId,DateUtil.beforeDay(beforeOneDay,1),beforeOneDay);
            Map<String, List<Map<String,Object>>> attendanceCollect = attendanceResult.stream().collect(Collectors.groupingBy(e->e.get("rq").toString()));
            clockIntime = attendanceCollect.get(beforeOneDay) == null?null:attendanceCollect.get(beforeOneDay).get(0);
            if (clockIntime == null || clockIntime.size() == 0){
                //取不到当天的就再往前取一天
                clockIntime = attendanceCollect.get(DateUtil.beforeDay(beforeOneDay,1)) == null?null:attendanceCollect.get(DateUtil.beforeDay(beforeOneDay,1)).get(0);
            }
        }
        if (clockIntime !=null && clockIntime.size()>0){
            for (int i=8;i>0;i--){
                String in  = Util.null2String(clockIntime.get("j"+i));
                String out  = Util.null2String(clockIntime.get("c"+i));
                if (!"".equals(out) && !"NULL".equals(out)){
                    if (DateUtil.getTime(out).compareTo(DateUtil.getTime(earliestTime)) > 0){
                        earliestTime = out;
                    }
                    break;
                }else if (!"".equals(in) && !"NULL".equals(in)){
                    if (DateUtil.getTime(in).compareTo(DateUtil.getTime(earliestTime)) > 0){
                        earliestTime = in;
                    }
                    break;
                }
            }
        }
        String finalEarliestTime = earliestTime;
        List<Map<String,Object>> resultList = clockInTimeList.stream().filter(e->{
            String signDate = e.get("signdate")+" "+e.get("signtime");
            if ((DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalEarliestTime)) >0)){
                return true;
            }else {
                return false;
            }
        }).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 有效打卡
     * @param effectiveclockInTimeList
     */
    public void clearRepeatClock(List<Map<String,Object>> effectiveclockInTimeList){
        Map<String,Object> gobalSet = ExtensionClassHolder.getGlobalSetMap();
        if (!Util.null2String(gobalSet.get("interval_minutes")).equals("")){
            for (int i=0;i<effectiveclockInTimeList.size()-1;i++){
                String time1 = effectiveclockInTimeList.get(i).get("signdate")+" "+effectiveclockInTimeList.get(i).get("signtime");
                for (int j=i+1;j<effectiveclockInTimeList.size();j++){
                    String time2 = effectiveclockInTimeList.get(j).get("signdate")+" "+effectiveclockInTimeList.get(j).get("signtime");
                    if (DateUtil.getBetWeenMinutes(time1,time2) <Integer.valueOf(gobalSet.get("interval_minutes").toString())){
                        effectiveclockInTimeList.remove(effectiveclockInTimeList.get(j));
                        j--;
                    }
                }
            }
        }
    }
}
